﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using WebcamLib;
using XaReadFiles;
using SocketLib;
using VideoCall.Properties;
using System.Reflection;
using MSR.LST.Net.Rtp;
using System.Runtime.InteropServices;


namespace VideoCall
{
    public partial class FrmVideoCall : Form
    {
        #region Size Webbrower
        int w = 415;
        int h = 202;
        #endregion

        #region Data
        DataProvider DuLieu = new DataProvider();
        #endregion

        #region Mediaplayer
        // choi nhac
        WMPLib.WindowsMediaPlayer wmp = new WMPLib.WindowsMediaPlayer();

        //mute
        public bool mute = false;
        private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
        private const int WM_APPCOMMAND = 0x319;
        [DllImport("user32.dll")]
        public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
        #endregion

        #region List Procesbar Send and Receive files
        List<ProcessBarSendFile.ProcessBarControl> ListFileSend = new List<ProcessBarSendFile.ProcessBarControl>();
        List<ProcessBarSendFile.ProcessBarControl> ListFileReceive = new List<ProcessBarSendFile.ProcessBarControl>();
        #endregion

        #region ORTHER
        public int YourID;
        // webfull
        bool webfull = false;

        public int stt;
        public int Current = 1;
        int numpart = 1024;
        public int portsendfile = 2500;
        #endregion

        #region From
        public FrmShowCall frmshowcall;
        public FrmCalling frmcall;
        #endregion

        #region User vs Group
        public string username;
        public string yourip;
        public string listgroup;
        public int _groupcurrent = 0;
        public bool master = false;
        public int numbermember;
        public int slider = 1;
        public int Maxslider;
        public int numberofslider = 5;
        #endregion

        #region Sound && WebCam
        
        public bool active = false;
        public MicLib.Microphone Mic = new MicLib.Microphone();
        public Webcam webcam = new Webcam(250);


        // Biến Dùng cho việc lưu file audio
        bool audio = false;
        NAudio.Wave.WaveFileWriter writeraudio;
        string folderaudio = "";

        // Biến dùng để lưu video
        bool start = false;
        bool video = false;
        AviFile.VideoStream VStream;
        AviFile.AviManager AManager;
        string foldervideo = "";
        string fileaudio = "";
        #endregion
        
        #region SOCKET
        //private MulticastUDP udp = null;
        //private MulticastUDP udpmic = null;
        #endregion
        
        public FrmVideoCall()
        {
            
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();

        }

        #region Truyen Video
        void webcam_GetBuffer(object sender, GetBufferEventArgs e)
        {
            if (e.Buffer != null && _groupcurrent != 0)
            {
                if (Checkslider(this.slider, this.stt) == true)
                {
                    byte[] header = new byte[2];
                    // groupname // kieu int
                    header[0] = (byte)_groupcurrent;
                    // so thu tu trong group
                    header[1] = (byte)stt;
                    SendVideo(header.Concat(e.Buffer).ToArray());
                }
            }
        }
        public static void ProcessVideo(PictureBox pictureBox, byte[] data)
        {
            Image img = Image.FromStream(new MemoryStream(data));
            //pictureBox.Image = img;
            Bitmap result = new Bitmap(pictureBox.Width, pictureBox.Height);
            using (Graphics g = Graphics.FromImage((Image)result))
                g.DrawImage(img, 0, 0, pictureBox.Width, pictureBox.Height);
            pictureBox.Image = result;
        }
        public void ProcessCurrent(byte[] data)
        {
            Image img = Image.FromStream(new MemoryStream(data));
            //_pic.Image = img;
            Bitmap result = new Bitmap(_pic.Width, _pic.Height);
            using (Graphics g = Graphics.FromImage((Image)result))
                g.DrawImage(img, 0, 0, _pic.Width, _pic.Height);
            _pic.Image = result;
            Bitmap bmp = new Bitmap(_pic.Image);
            // chỗ này lưu video
            if (video == true)
            {
                if (start == false)
                {
                    //add a new video stream and one frame to the new file
                    VStream = AManager.AddVideoStream(true, 4, bmp);
                    VStream.AddFrame(bmp);
                    start = true;
                }
                VStream.AddFrame(bmp);
            }
        }
        #endregion

        #region Truyền Microphone
        void Mic_RecieveData(object sender, MicLib.RecieveDataEventArgs e)
        {
            if (e.Buffer != null && _groupcurrent != 0)
            {
                byte[] header = new byte[2];
                header[0] = (byte)_groupcurrent;
                header[1] = (byte)YourID;
                byte[] arr = header.Concat(e.Buffer).ToArray();
                SendAudio(arr);
            }
        }
        #endregion

        private void FrmVideoCall_Load(object sender, EventArgs e)
        {
            //this.WindowState = FormWindowState.Maximized;
            // khỏi tạo RTP muticast cho group
            //RTPMulticast(YourID, "224.5.6.7", port_video);
            
            webcam.GetBuffer += new Webcam.GetBufferEventHandler(webcam_GetBuffer);
            Mic.RecieveData += new MicLib.Microphone.RecieveDataEventHandler(Mic_RecieveData);
            webcam.Start();
            try
            {
                string str = DuLieu.GetAvatar();
                if (str != "null")
                {
                    Bitmap bmp = new Bitmap(str);
                    picavatar.BackgroundImage = bmp;
                    picavatar.BackgroundImageLayout = ImageLayout.Stretch;
                }
            }
            catch (Exception) { }
            
            FileInfo fl = new FileInfo("Resources\\box.png");
            XaReadFiles.ReadFiles red = new ReadFiles();
            this.webBrowser1.Navigate(red.LoadDocument(red.LoadDocument(fl.FullName)));
            refresh_picturebox();
        }

        #region Delegate frmlogin
        public delegate void VideoCallGui(string data);
        public event VideoCallGui Send = null;
        public virtual void OnNutDaNhan(string data)
        {
            if (Send != null)
                Send(data);
        }
        #endregion

        #region FrmShowCall
        void frmshowcall_Ex(string data)
        {
            // goi lenh huy qua server
            OnNutDaNhan("CancelCalling|" + data);
            frmshowcall.Close();
        }
        #endregion

        #region FrmCalling
        void frmcall_Ans(string data)
        {
            OnNutDaNhan("AnswerCalling|" + data);
            frmcall.Close();
        }
        public void ShowCalling(string user)
        {
            frmcall = new FrmCalling();
            frmcall._name = user;
            frmcall.Ans += new FrmCalling.Answer(frmcall_Ans);
            frmcall.label1.Text = user + " mời bạn tham gia cuộc gọi?";
            frmcall.Show();
        }
        #endregion

        #region Hàm Active && Drop Cuộc Gọi
        public void Create_RTP_Muticast(string data)
        {
            string[] muti = data.Split('*');
            RTPMulticast(YourID, muti[0], int.Parse(muti[1]));
        }
        public void ActiveCall(int grp)
        {
            this._groupcurrent = grp;
            Resume();
            if (active == false)
            {
                Mic.Start();
                //Mic.Resume();
                //webcam.Start();
                webcam.Resume();
            }
            else
            {
               // Mic.Resume();
                webcam.Resume();
            }
            lsbshowchat.Items.Clear();
            lsbshowchat.Controls.Clear();
               
        }
        public void DropCall()
        {
            Stop();
            this._groupcurrent = 0;
            webcam.Pause();
            Mic.Pause();
            active = true;
            refresh_picturebox();
            lsbshowchat.Controls.Clear();
            ListFileReceive.Clear();
            ListFileSend.Clear();
            // kết thúc việc ghi file audio-data time.now
            btnsaveaudio.Enabled = true;
            audio = false;
            try
            {
                writeraudio.Close();
            }
            catch (Exception){}
            // kết thúc việc ghi file video-data time.now
            
            
            // ghep am thanh vao video
            if (start == true)
            {
                AManager.AddAudioStream(fileaudio, 0);
                File.Delete(fileaudio);
            }
            btnsavevideo.Enabled = true;
            video = false;
            try
            {
                AManager.Close();
            }
            catch (Exception) { }

            start = false;
        }
        #endregion

        #region Nhóm Hàm Update Group, Update ListUser
        public void UpdateContacts(string contact)
        {
            listBox1.Items.Clear();
            listBox1.Controls.Clear();
            string[] temp = contact.Split(',');

            int count = temp.Length + ((temp.Length * 5) / 13 + 1) + ((temp.Length * 15) / 13 + 1);
            for (int i = 0; i < count; i++)
                listBox1.Items.Add("");
            int n1 = 10;
            for (int i = 0; i < temp.Length; i++)
            {
                string[] us = temp[i].Split('*');
                Label lb = new Label();
                lb.Text = us[0];
                lb.BackColor = Color.Transparent;
                lb.ForeColor = System.Drawing.SystemColors.ActiveCaption;
                lb.Font = new Font("Verdana", 11, FontStyle.Bold);
                lb.Visible = true;
                lb.Size = new Size(140, 18);
                lb.Name = temp[i];
                if (listBox1.Controls.Count == 0)
                    n1 = 10;
                else
                    n1 = listBox1.Controls[listBox1.Controls.Count - 1].Location.Y + lb.Size.Height + 20;
                lb.Location = new Point(0, n1);

                Button btncall = new Button();
                btncall.BackgroundImage = new Bitmap(Resources._call);
                btncall.BackgroundImageLayout = ImageLayout.Stretch;
                btncall.Name = lb.Name;
                btncall.Size = new Size(35, 30);
                btncall.Location = new Point(lb.Size.Width, n1 - 7);
                btncall.Click += new EventHandler(btncall_Click);

                listBox1.Controls.Add(lb);
                listBox1.Controls.Add(btncall);
            }
        }
        public void UpDataListGroup()
        {
            listBox2.Controls.Clear();
            listBox2.Items.Clear();
            int n1 = 25;
            if (listgroup != null)
            {
                string[] list = listgroup.Split('*');

                //lable ten cuoc goi = 18       pic tick = 25
                //6
                //lable danh sach client = 18
                //6
                //button jon & button Endcall = 30
                //6

                // 7 = (18+6+18+6+30+6)/13 + 1;

                int count = list.Length * 7;
                for (int i = 0; i < count; i++)
                    listBox2.Items.Add("");

                
                for (int i = 0; i < list.Length; i++)
                {
                    // khoi tao
                    Label lbcuocgoi = new Label();
                    PictureBox pic = new PictureBox();
                    Label lbdanhsach = new Label();
                    Button btn_endcall = new Button();
                    btn_endcall.Enabled = false;
                    Button btn_join = new Button();

                    string[] user = list[i].Split('?');
                    lbcuocgoi.Enabled = false;
                    lbcuocgoi.Cursor = Cursors.Hand;
                    lbcuocgoi.Text = "Cuộc Gọi " + user[0];
                    lbcuocgoi.BackColor = Color.Transparent;
                    lbcuocgoi.ForeColor = System.Drawing.SystemColors.ControlText;
                    lbcuocgoi.Font = new Font("Verdana", 11, FontStyle.Bold);
                    lbcuocgoi.Visible = true;
                    lbcuocgoi.Size = new Size(125, 18);
                    lbcuocgoi.Name = user[0];

                    if (listBox2.Controls.Count == 0)
                        n1 = 25;
                    else
                        n1 = listBox2.Controls[listBox2.Controls.Count - 1].Location.Y + listBox2.Controls[listBox2.Controls.Count - 1].Size.Height + 6;
                    // kiem tra nhung cai group nao co chứa, username cua minh thi hien len cai anh active
                    // và đặt lệnh click cho ở trên.
                    lbcuocgoi.Location = new Point(10, n1);

                    pic.Size = new Size(25, 25);
                    pic.Visible = false;
                    pic.BackColor = Color.Wheat;
                    pic.BackgroundImage = new Bitmap(Resources.tick);
                    pic.BackgroundImageLayout = ImageLayout.Stretch;
                    pic.Location = new Point(lbcuocgoi.Location.X + lbcuocgoi.Size.Width, lbcuocgoi.Location.Y - 5);


                    lbdanhsach.AutoSize = false;
                    string[] tach = user[1].Split(',');
                    lbdanhsach.Text = user[1];
                    for (int j = 0; j < tach.Length; j++)
                    {
                        //string[] lbtext = tach[j].Split('+');
                        // cho này làm cho hiện cái pic thể hiện active của group
                        if (username== tach[j])
                        {
                            btn_join.Enabled = false;
                            pic.Visible = true;
                            btn_endcall.Enabled = true;
                            lbcuocgoi.Enabled = true;
                            btn_endcall.Click += new EventHandler(btn_endcall_Click);
                        }
                    }
                    lbdanhsach.TextAlign = ContentAlignment.MiddleCenter;
                    lbdanhsach.BackColor = Color.Transparent;
                    lbdanhsach.ForeColor = System.Drawing.SystemColors.ActiveCaption;
                    lbdanhsach.Font = new Font("Verdana", 8, FontStyle.Bold);
                    lbdanhsach.Visible = true;
                    lbdanhsach.Size = new Size(190, 30);
                    lbdanhsach.TextAlign = ContentAlignment.MiddleCenter;
                    lbdanhsach.Location = new Point(lbcuocgoi.Location.X - 20, lbcuocgoi.Location.Y + 6 + lbcuocgoi.Size.Height);

                    btn_endcall.Name = lbcuocgoi.Name;
                    btn_endcall.Size = new Size(35, 30);
                    btn_endcall.BackColor = Color.Transparent;
                    btn_endcall.BackgroundImage = new Bitmap(Resources.endcall);
                    btn_endcall.BackgroundImageLayout = ImageLayout.Stretch;
                    btn_endcall.Cursor = Cursors.Hand;
                    btn_endcall.Location = new Point(lbdanhsach.Location.X + 60, lbdanhsach.Location.Y + lbdanhsach.Size.Height + 6);

                    btn_join.Name = lbcuocgoi.Name;
                    btn_join.Size = new Size(35, 30);
                    btn_join.Click += new EventHandler(btn_join_Click);
                    btn_join.BackColor = Color.Transparent;
                    btn_join.BackgroundImage = new Bitmap(Resources.join);
                    btn_join.BackgroundImageLayout = ImageLayout.Stretch;
                    btn_join.Cursor = Cursors.Hand;
                    btn_join.Location = new Point(btn_endcall.Location.X + btn_endcall.Size.Width + 10, btn_endcall.Location.Y);

                    listBox2.Controls.Add(lbcuocgoi);
                    listBox2.Controls.Add(pic);
                    listBox2.Controls.Add(lbdanhsach);
                    listBox2.Controls.Add(btn_endcall);
                    listBox2.Controls.Add(btn_join);
                }
            }
        }
        public void UpDataCurrentList(List<EndPoint> ListEndPoint)
        {
            refresh_picturebox();
            int dem = 0;
            foreach (EndPoint ep in ListEndPoint)
            {
                dem++;
                string[] temp = ep.ToString().Split(':');
                if (temp[0] == yourip)
                    stt = dem;
            }

        }
        #endregion

        #region Lầy Đường Dẫn
        public static string GetBasePath()
        {
            return Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.Replace("file:///", ""));
        }
        #endregion

        /// <summary>
        /// Nhóm Hàm Thao Tác Trên Hệ Thống
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        #region Thao Tác Gọi
        void btncall_Click(object sender, EventArgs e)
        {

            Button btn = (Button)sender;
            string[] temp = btn.Name.Split('*');
            if (temp[1] != YourID.ToString())
            {
                OnNutDaNhan("Call|" + temp[1]);
                frmshowcall = new FrmShowCall();
                frmshowcall.Ex += new FrmShowCall.Exit(frmshowcall_Ex);
                frmshowcall.username = temp[0];
                frmshowcall.ShowDialog();
            }
        }
        #endregion

        #region Clock
        private void clock1_Load(object sender, EventArgs e)
        {
            clock1.UtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
        }
        #endregion

        #region Đổi avarta
        private void button5_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.Filter = "JPEG|*.jpg|GIF|*.gif|PNG|*.png";
            Bitmap bm;
            if (op.ShowDialog() == DialogResult.OK)
            {    
                DuLieu.UpdataAvarta(op.FileName);
                bm = new Bitmap(op.FileName);
                picavatar.BackgroundImage = bm;
                picavatar.BackgroundImageLayout = ImageLayout.Stretch;
            }
        }
        #endregion
        
        #region Hành Động Đổi Mật Khẩu
        private void button8_Click(object sender, EventArgs e)
        {
            frmChangePassword frmchange = new frmChangePassword();
            frmchange.Change += new frmChangePassword.ChangePass(frmchange_Change);
            frmchange.ShowDialog();
        }
        void frmchange_Change(string data)
        {
            OnNutDaNhan("ChangePassword|" + data);
        }
        #endregion

        #region Hiện Thông Báo Bất Kỳ
        public void Showmessage(string data)
        {
            MessageBox.Show(data, "VideoCall - frmvideocall show messages()", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        #endregion

        #region Join Vào 1 Group
        void btn_join_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            if (MessageBox.Show("Gửi yêu Cầu Xin Vào Group " + btn.Name + " ?", "VideoCall - Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                OnNutDaNhan("Join|" + btn.Name);
        }
        #endregion

        #region Kết Thúc Cuộc Gọi
        void btn_endcall_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            if (MessageBox.Show("Rời Khỏi Cuộc Gọi " + btn.Name + " ?", "VideoCall - Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                OnNutDaNhan("EndCall|" + btn.Name);
        }
        #endregion

        #region Times refresh Danh Ba Va List Group
        private void timer1_Tick(object sender, EventArgs e)
        {
            listBox1.Refresh();
            listBox2.Refresh();
            lsbshowchat.Refresh();
            
        }
        #endregion

        #region FullScreen Hộp Hiển thị nội dung
        private void linkfull_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            webfull = true;
            webBrowser1.Location = new Point(0, 00);
            webBrowser1.Width = this.Width;
            webBrowser1.Height = this.Height;

            // Ẩn tất cả các control còn lại
            foreach (Control ctl in this.Controls)
                if (ctl.Name != "webBrowser1")
                    ctl.Visible = false;
            // Hiện 2 nút tắt và print
            btn_full_1.Visible = true;
            btn_print_1.Visible = true;
  
        }
        private void btn_full_1_Click_1(object sender, EventArgs e)
        {
            this.webBrowser1.Location = new Point(816, 22);
            this.webBrowser1.Size = new Size(w, h);
            // Hiện tất cả các control còn lại
            foreach (Control ctl in this.Controls)
                    ctl.Visible = true;
            btnexitvideofull.Visible = false;
            btn_full_1.Visible = false;
            btn_print_1.Visible = false;
        }

        private void btn_print_1_Click_1(object sender, EventArgs e)
        {
            this.webBrowser1.Print();
        }
        #endregion

        #region Tắt Chế độ FullScreen của hộp hiển thị nội dung
        #endregion

        #region Send Chat
        private void button4_Click(object sender, EventArgs e)
        {
            if (txtchat.Text != null)
            {
                if (_groupcurrent != 0)
                    SendChat(Encoding.Unicode.GetBytes(username + " : " + txtchat.Text));
            }
            txtchat.Text = "";
        }
        #endregion

        #region Sự Kiện FromClosing
        private void FrmVideoCall_FormClosing(object sender, FormClosingEventArgs e)
        {
            OnNutDaNhan("Bye|");
        }
        #endregion

        #region Refresh picturebox
        public void refresh_picturebox()
        {
            Bitmap bitmap = new Bitmap(Resources.novideo);
            _pic.Image = bitmap;
            _pic.SizeMode = PictureBoxSizeMode.CenterImage;
            pictureBox1.Image = bitmap;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox2.Image = bitmap;
            pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox3.Image = bitmap;
            pictureBox3.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox4.Image = bitmap;
            pictureBox4.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox5.Image = bitmap;
            pictureBox5.SizeMode = PictureBoxSizeMode.StretchImage;
            
            //_pic.BackgroundImage = bitmap;
            //pictureBox1.BackgroundImage = bitmap;
            //pictureBox2.BackgroundImage = bitmap;
            //pictureBox3.BackgroundImage = bitmap;
            //pictureBox4.BackgroundImage = bitmap;
            //pictureBox5.BackgroundImage = bitmap;

            // ké thêm cái refresh listbox chat
            lsbshowchat.Items.Clear();
            if(_groupcurrent == 0)
                this.lbnamecallcurrent.Text = "Bạn Hiện Không Ở Cuộc Gọi Nào";
            this.lbnamecallcurrent.Visible = true;
        }
        #endregion

        #region Chuyển đổi ảnh lớn
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Current = 1;
        }
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            Current = 2;
        }

        private void pictureBox3_Click(object sender, EventArgs e)
        {
            Current = 3;
        }

        private void pictureBox4_Click(object sender, EventArgs e)
        {
            Current = 4;
        }

        private void pictureBox5_Click(object sender, EventArgs e)
        {
            Current = 5;
        }
        #endregion

        #region SendFileToClient
        public void SendFileToClient(string ip, int id)
        {
            ListFileSend[id].RunSend(ip);
        }
        #endregion

        #region Add text chat
        public void AddChat(string chattext)
        {
            PlayMusic("message", false);
            lsbshowchat.Refresh();
            TextBox txtchat = new TextBox();
            txtchat.BorderStyle = BorderStyle.None;
            txtchat.Height = 18;
            txtchat.Width = 590;
            txtchat.Text = chattext;
            txtchat.Visible = true;
            if (lsbshowchat.Controls.Count == 0)
                txtchat.Location = new Point(0, 10);
            else
                txtchat.Location = new Point(0,lsbshowchat.Controls[lsbshowchat.Controls.Count - 1].Location.Y  + 20);
            lsbshowchat.Items.Clear();
            for (int i = 0; i < lsbshowchat.Controls.Count * 4;i++ )
                lsbshowchat.Items.Add("");
            lsbshowchat.Controls.Add(txtchat);
        }
        #endregion

        #region Nút mở file
        private void pictureBox12_Click(object sender, EventArgs e)
        {
            if (_groupcurrent != 0)
            {
                OpenFileDialog op = new OpenFileDialog();
                op.Filter = "Any|*.*";
                if (op.ShowDialog() == DialogResult.OK)
                {
                    lsbshowchat.Items.Clear();
                    for (int i = 0; i < lsbshowchat.Controls.Count * 4; i++)
                        lsbshowchat.Items.Add("");
                    // add thông báo đang gửi file tới thành viên trong nhóm.
                    AddChat(" File : "+ op.FileName);
                    // khởi tạo đối tượng processbarcontrol
                    ProcessBarSendFile.ProcessBarControl pro = new ProcessBarSendFile.ProcessBarControl();
                    pro.ThongTinProcessBar += new ProcessBarSendFile.ProcessBarControl.ProcessBarNutNhan(pro_ThongTinProcessBar);
                    pro.SetupSend(numbermember - 1, op.FileName, ListFileSend.Count,portsendfile,numpart);
                    // xác định location của processbarcontrol
                    pro.Location = new Point(0, lsbshowchat.Controls[lsbshowchat.Controls.Count - 1].Location.Y + 20);
                    ListFileSend.Add(pro);
                    
                    string[] tenfile = op.FileName.Split('\\');
                    FileStream fs = File.OpenRead(op.FileName);

                    SendFile(Encoding.Unicode.GetBytes("CHAT|"+username + "*" + YourID + "*" + yourip + "*" + ListFileSend[ListFileSend.Count - 1].ID + "*" + tenfile[tenfile.Count() - 1] + "*" + fs.Length + "*" + numpart+"*"+portsendfile));
                    OnNutDaNhan("SendFile|"+_groupcurrent);
                    lsbshowchat.Controls.Add(pro);

                }

            }
        }

        #region Lệnh Từ ProcessBar gửi lên
        void pro_ThongTinProcessBar(string data)
        {
            string []msg = data.Split('|');
            if (msg[0] == "CancelSend") // Hủy Truyền File
                SendFile(Encoding.Unicode.GetBytes("CancelSend|"+msg[1]));
            else // Hủy Nhận
            {
                SendFile(Encoding.Unicode.GetBytes("CancelReceive|" + msg[1] + "|" + msg[2] + "|" + this.yourip));
            }
        }
        #endregion
        
        #endregion

        #region Nút in
        private void pictureBox13_Click(object sender, EventArgs e)
        {
            webBrowser1.Print();
        }
        #endregion

        #region Thanh Trượt
        private void picright_Click(object sender, EventArgs e)
        {
            // Kiểm tra mình có phải là master của group ko
            if (master == true)
            {
                if (slider < Maxslider)
                {
                    slider++;
                    // gởi lệnh tăng slider lên server
                    OnNutDaNhan("Slider|" + _groupcurrent + "|" + slider);
                }
            }
        }

        private void picleft_Click(object sender, EventArgs e)
        {
            // Kiểm tra mình có phải là master của group ko
            if (master == true)
            {
                if (slider > 1)
                {
                    slider--;
                    // gởi lệnh giảm slider lên server
                    OnNutDaNhan("Slider|" + _groupcurrent + "|" + slider);
                }
            }
        }
        private bool Checkslider(int slider, int thisstt)
        {
            int kq = thisstt / numberofslider;
            if (thisstt % numberofslider > 0)
            {
                if (slider == kq + 1)
                    return true;
                else return false;
            }
            else
            {
                if (slider == kq)
                    return true;
                else return false;
            }
        }
        #endregion

        private void EventKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Space:
                    Mic.Resume();
                    break;
            }
        }
        private void EventKeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Space:
                    Mic.Pause();
                    break;
            }
        }

        private void txtchat_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Space:
                    Mic.Resume();
                    break;
                case Keys.Enter:
                    if (txtchat.Text != null)
                    {
                        if(_groupcurrent != 0)
                            SendChat(Encoding.Unicode.GetBytes(username + " : " + txtchat.Text));
                    }
                    txtchat.Text = "";
                    break;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                checkBox1.Font = new Font(checkBox1.Font, FontStyle.Bold);
                Mic.Resume();
            }
            else
            {
                checkBox1.Font = new Font(checkBox1.Font, FontStyle.Regular);
                Mic.Pause();
            }
        }

        private void lsbshowchat_Click(object sender, EventArgs e)
        {
            Refresh();
        }

        #region Hàm chơi nhạc
        public void PlayMusic(string style, bool setting)
        {
            wmp.settings.setMode("loop",false);
            try
            {
                wmp.controls.stop();
                switch (style)
                {
                    case "login":
                        wmp.URL = "media\\login.mp3";
                        break;
                    case "call":
                        wmp.URL = "media\\call.mp3";
                        break;
                    case "calling":
                        wmp.URL = "media\\calling.mp3";
                        break;
                    case "message":
                        wmp.URL = "media\\message.mp3";
                        break;
                }
                if (setting == true)
                    wmp.settings.setMode("loop", true);
                wmp.controls.play();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "VideoCall - Playmusic", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        public void StopMusic()
        {
            try
            {
                wmp.controls.stop();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "VideoCall - Playmusic", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region Hàm MUTE/ UNMUTE
        private void button1_Click(object sender, EventArgs e)
        {
            if (_groupcurrent != 0)
            {
                SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE);
                if (mute == false)
                {
                    mute = true;
                    btnmute.BackgroundImage = new Bitmap(Resources.mute);
                }
                else
                {
                    mute = false;
                    btnmute.BackgroundImage = new Bitmap(Resources.speaker);
                }
            }
        }
        #endregion

        #region Save Audio
        private void btnsaveaudio_Click(object sender, EventArgs e)
        {
            if (_groupcurrent != 0)
            {
                if (video != true)
                {
                    FolderBrowserDialog fl = new FolderBrowserDialog();
                    if (fl.ShowDialog() == DialogResult.OK)
                    {
                        btnsaveaudio.Enabled = false;
                        folderaudio = fl.SelectedPath;
                        NAudio.Wave.WaveFormat fo = new NAudio.Wave.WaveFormat(8000, 1);
                        string filename = fl.SelectedPath + "\\audio-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + ".mp3";
                        writeraudio = new NAudio.Wave.WaveFileWriter(new FileStream(filename, FileMode.Create), fo);
                        audio = true;
                    }
                }
                else
                    MessageBox.Show("Bạn đang ở chế độ lưu video", "VideoCall - Save Audio", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region Save Video
        private void btnsavevideo_Click(object sender, EventArgs e)
        {
            if (_groupcurrent != 0)
            {
                if (audio != true)
                {
                    FolderBrowserDialog fl = new FolderBrowserDialog();
                    if (fl.ShowDialog() == DialogResult.OK)
                    {
                        if (video == false)
                        {
                            btnsavevideo.Enabled = false;
                            foldervideo = fl.SelectedPath;
                            string filename = fl.SelectedPath + "\\Video-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + ".avi";
                            File.WriteAllText(filename, "0");
                            AManager = new AviFile.AviManager(filename, false);
                            
                            
                            NAudio.Wave.WaveFormat fo = new NAudio.Wave.WaveFormat(8000, 1);
                            fileaudio = "audio.mp3";
                            writeraudio = new NAudio.Wave.WaveFileWriter(new FileStream(fileaudio, FileMode.Create), fo);

                            audio = true;
                            video = true;
                        }
                    }
                }
                else
                    MessageBox.Show("Bạn đang ở chế độ lưu Audio", "VideoCall - Save Video", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region FullScreen Video
        private void btnvideofullscreen_Click(object sender, EventArgs e)
        {
            if (_groupcurrent != 0)
            {
                _pic.Location = new Point(0, 00);
                _pic.Width = this.Width;
                _pic.Height = this.Height;

                // Ẩn tất cả các control còn lại
                foreach (Control ctl in this.Controls)
                    if (ctl.Name != "_pic")
                        ctl.Visible = false;
                // Hiện 2 nút tắt và print
                btnexitvideofull.Visible = true;
            }
        }

        private void btnexitvideofull_Click(object sender, EventArgs e)
        {
            this._pic.Location = new Point(10, 13);
            this._pic.Size = new Size(596, 407);
            // Hiện tất cả các control còn lại
            foreach (Control ctl in this.Controls)
                ctl.Visible = true;
            btnexitvideofull.Visible = false;
            btn_full_1.Visible = false;
            btn_print_1.Visible = false;
        }
        #endregion

        private void FrmVideoCall_Resize(object sender, EventArgs e)
        {
            if (webfull == false)
            {
                w = webBrowser1.Width;
                h = webBrowser1.Height;
            }
        }

    }
}
